package it.koutifaris.travianmap.worldmap;

import it.koutifaris.travianmap.db.TileMapDAL;
import it.koutifaris.travianmap.model.MapSquare;

import java.util.Iterator;

import android.graphics.Rect;

public class WorldMap {

	private MapCache cache;
	private TileMapDAL mapDAO;

	public WorldMap(MapCache cache, TileMapDAL mapDAO) {
		this.cache = cache;
		this.mapDAO = mapDAO;
	}

	public WorldMap(TileMapDAL mapDAO) {
		this.cache = new MapCacheImpl();
		this.mapDAO = mapDAO;
	}

	public MapSquare getSquare(int x, int y) {
		XY xy = new XY(x, y);
		MapSquare mapSquare = cache.getMapSquare(xy);
		if (mapSquare == null) {
			loadTile(x, y);
		}
		mapSquare = cache.getMapSquare(xy);
		if (mapSquare == MapCache.NULL_SQUARE)
			return null;

		return mapSquare;
	}

	public int getBorderSize() {
		return 100;
	}

	private void loadTile(int x, int y) {
		Iterator<MapSquare> it = mapDAO.getTile(x, y).iterator();
		while (it.hasNext()) {
			MapSquare sq = it.next();
			XY xy = new XY(sq.getX(), sq.getY());
			if (cache.getMapSquare(xy) == null) {
				if (sq.getVillage() == null) {
					cache.setMapSquare(xy, MapCache.NULL_SQUARE);
				} else {
					cache.setMapSquare(xy, sq);
				}
			}
		}
	}

	public Rect getBounds() {
		return mapDAO.getBounds();
	}

}
